package com.bmps.springcloud.insuredmicroservice.service.accept;

import com.bmps.springcloud.common.response.TaskResponseModel;
import com.bmps.springcloud.insuredmicroservice.config.accept.ProductConfig;
import com.bmps.springcloud.insuredmicroservice.constant.accept.AcceptConstant;
import com.bmps.springcloud.insuredmicroservice.constant.accept.AgencyConstant;
import com.bmps.springcloud.insuredmicroservice.constant.accept.RiskConstant;
import com.bmps.springcloud.insuredmicroservice.constant.accept.UnderWriteConstant;
import com.bmps.springcloud.insuredmicroservice.model.accept.resquest.*;
import com.bmps.springcloud.insuredmicroservice.service.RedisService;
import com.bmps.springcloud.insuredmicroservice.util.accept.AcceptUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author lyw
 * @date 2019-09-04 17:04:09
 */
@Service
public class HistoryVerificationServiceImpl implements HistoryVerificationService {
    private static Logger logger = LoggerFactory.getLogger(HistoryVerificationServiceImpl.class);
    private final RedisService redisService;
    private final InsuranceAcceptCoreService insuranceAcceptCoreService;
    private final ProductConfig productConfig;

    public HistoryVerificationServiceImpl(RedisService redisService, InsuranceAcceptCoreService insuranceAcceptCoreService, ProductConfig productConfig) {
        this.redisService = redisService;
        this.insuranceAcceptCoreService = insuranceAcceptCoreService;
        this.productConfig = productConfig;
    }

    @Override
    public TaskResponseModel checkHistoryVerification(String key, RequestModel requestModel) {
        logger.info("-------------历史核保任务-------------");
        List<InsurantModel> insurantModelList = requestModel.getCustInfo().getInsurants().getInsurant();
        //投保书号
        String prtNo = requestModel.getPolicyInfo().getPrtNo();
        for (InsurantModel insurantModel : insurantModelList) {
            try {
                String exists = insuranceAcceptCoreService.getHistoryVerificationContno(insurantModel.getInsuredNo());
                if (StringUtils.isEmpty(exists)) {
                    continue;
                }
                if (insurantModel.getBlackListFlag() > 0) {
                    return createTaskResponseModel(key, false);
                }
                if (insurantModel.getClaimFlag() > 0) {
                    return createTaskResponseModel(key, false);
                }
                exists = insuranceAcceptCoreService.queryRiskAndInsurance(insurantModel.getInsuredNo());
                if (StringUtils.equals(exists, "1") || insuranceAcceptCoreService.getSpecialAnnal(prtNo, insurantModel.getInsuredNo()) > 0) {
                    return createTaskResponseModel(key, false);
                }
            } catch (Exception e) {
                logger.error("在线核保任务校验失败：" + e.getMessage());
                TaskResponseModel taskResponseModel = new TaskResponseModel();
                taskResponseModel.setKey(AcceptConstant.TASK_ERROR);
                taskResponseModel.setResultMessage("在线核保任务校验失败:" + AcceptConstant.RESULT_FAIL_MESSAGE);
                return taskResponseModel;
            }
        }
        List<ProductModel> productModelList = requestModel.getProductInfo().getProducts().getProduct();
        for (ProductModel productModel : productModelList) {
            if (isExemption(productModel.getProdCode())) {
                AppntModel appntModel = requestModel.getCustInfo().getAppnt();
                try {
                    String exists = insuranceAcceptCoreService.getHistoryVerificationContno(appntModel.getAppntNo());
                    if (StringUtils.isEmpty(exists)) {
                        continue;
                    }
                    if (appntModel.getClaimFlag() > 0) {
                        return createTaskResponseModel(key, false);
                    }
                    if (appntModel.getBlackListFlag() > 0) {
                        return createTaskResponseModel(key, false);
                    }
                    exists = insuranceAcceptCoreService.queryRiskAndInsurance(appntModel.getAppntNo());
                    if (StringUtils.equals(exists, "1") || insuranceAcceptCoreService.getSpecialAnnal(prtNo, appntModel.getAppntNo()) > 0) {
                        return createTaskResponseModel(key, false);
                    }
                } catch (Exception e) {
                    logger.error("在线核保任务校验失败：" + e.getMessage());
                    TaskResponseModel taskResponseModel = new TaskResponseModel();
                    taskResponseModel.setKey(AcceptConstant.TASK_ERROR);
                    taskResponseModel.setResultMessage("在线核保任务校验失败:" + AcceptConstant.RESULT_FAIL_MESSAGE);
                    return taskResponseModel;
                }
            }
        }
//        return this.createTaskResponseModel(key, true);
        //增加 加费 、拒保、特约校验
        return this.checkHistoryVerification(requestModel).setKey(key);
    }

    private TaskResponseModel checkHistoryVerification(RequestModel requestModel) {
        //投保书号
        String prtNo = requestModel.getPolicyInfo().getPrtNo();
        //险种
        List<ProductModel> productModels = requestModel.getProductInfo().getProducts().getProduct();
        //被保人
        List<InsurantModel> insurantModels = requestModel.getCustInfo().getInsurants().getInsurant();
        //投保人
        AppntModel appntModel = requestModel.getCustInfo().getAppnt();
        Set<InsurantModel> insurantModelSet = new HashSet<>(insurantModels.size());
        boolean isExemption = false;
        for (ProductModel product : productModels) {
            if (!productConfig.getNoPastCheckList().contains(product.getProdCode())) {
                InsurantModel insurantModel = AcceptUtil.getInsurantModelBySeq(product.getProdInsSeq(), insurantModels);
                insurantModelSet.add(insurantModel);
                if (!isExemption) {
                    isExemption = redisService.exemptionProduct(product.getProdCode()) ||
                            redisService.isExemptDuty(product.getProdCode(), appntModel,
                                    insurantModel, requestModel.getPolicyInfo().getPolApplyDate());
                }
            }
        }
        int flag;
        if (CollectionUtils.isNotEmpty(insurantModelSet)) {
            for (InsurantModel insurantModel : insurantModelSet) {
                flag = insuranceAcceptCoreService.getSpecialAnnal(prtNo, insurantModel.getInsuredNo());
                if (excludeAddingPremiumAnnal(insurantModel, productModels, requestModel.getPolicyInfo()) && (1 & flag) == 1) {
                    //如果存在不校验既往加费的险种 结果 -1
                    flag -= 1;
                }
                if (flag > 0) {
                    return createTaskResponseModel(flag, true, insurantModel.getName());
                }
            }
        }
        if (isExemption) {
            flag = insuranceAcceptCoreService.getSpecialAnnal(prtNo, appntModel.getAppntNo());
            if (flag > 0) {
                return createTaskResponseModel(flag, false, appntModel.getAppntName());
            }
        }
        return new TaskResponseModel().setResultCode(AcceptConstant.RESULT_SUCCESS_CODE).setResultMessage(AcceptConstant.RESULT_SUCCESS_MESSAGE);
    }

    private TaskResponseModel createTaskResponseModel(int digital, boolean flag, String name) {
        TaskResponseModel taskResponseModel = new TaskResponseModel();
        taskResponseModel.setResultCode(UnderWriteConstant.UNDER_WRITE_UNDEFINED);
        if ((1 & digital) == 1) {
            return taskResponseModel.setResultMessage(String.format(flag ? UnderWriteConstant.UNDERWRITE_NUGG0057_MESSAGE : UnderWriteConstant.UNDERWRITE_NUGG0054_MESSAGE, name));
        } else if ((2 & digital) == 2) {
            return taskResponseModel.setResultMessage(String.format(flag ? UnderWriteConstant.UNDERWRITE_NUGG0059_MESSAGE : UnderWriteConstant.UNDERWRITE_NUGG0056_MESSAGE, name));
        } else if ((4 & digital) == 4) {
            return taskResponseModel.setResultMessage(String.format(flag ? UnderWriteConstant.UNDERWRITE_NUGG0058_MESSAGE : UnderWriteConstant.UNDERWRITE_NUGG0055_MESSAGE, name));
        }
        return taskResponseModel;
    }

    private TaskResponseModel createTaskResponseModel(String key, boolean flag) {
        TaskResponseModel taskResponseModel = new TaskResponseModel();
        taskResponseModel.setKey(key);
        if (flag) {
            taskResponseModel.setResultCode(AcceptConstant.RESULT_SUCCESS_CODE);
            taskResponseModel.setResultMessage(AcceptConstant.RESULT_SUCCESS_MESSAGE);
        } else {
            taskResponseModel.setResultCode(AcceptConstant.RESULT_FAIL_CODE);
            taskResponseModel.setResultMessage(AcceptConstant.VERIFICATION_MESSAGE);
        }
        return taskResponseModel;
    }

    /**
     * 判断险种是否为豁免险
     *
     * @param riskCode 险种编号
     * @return boolean
     */
    private boolean isExemption(String riskCode) {
        Object obj = redisService.get(AcceptConstant.REDIS_PREFIX_R004 + "|" + riskCode);
        if (obj != null) {
            String[] a = obj.toString().split("\\|");
            return StringUtils.equals(a[4], "1") || StringUtils.equals(a[4], "2");
        }
        return false;
    }

    private boolean excludeAddingPremiumAnnal(InsurantModel insurant, List<ProductModel> productModels, PolicyInfoModel policyInfoModel) {
        //是否校验既往加费
        String agencyCode = policyInfoModel.getAgencyCode();
        if (StringUtils.equals(AgencyConstant.HZ01, agencyCode)) {
            for (ProductModel productModel : productModels) {
                if (productModel.getProdInsSeq() == insurant.getInsSeq()) {
                    if (StringUtils.equals(RiskConstant.HCT010, productModel.getProdCode())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
